from flask import Blueprint, request, jsonify
from flask_cors import cross_origin
from app import db
from app.models import User
import base64
import os

bp = Blueprint('api', __name__)

@bp.route('/api/announcement')
@cross_origin()
def get_announcement():
    """获取公告内容"""
    announcement_data = {
        'title': '想云湾·锦地轩全体业主联署公告',
        'date': '2025年7月25日',
        'content': {
            'reason': '鉴于本小区东门长期封闭导致居民绕行不便（日均多耗费15分钟通勤时间），且存在消防通道被占用隐患，经前期238户业主民意调查显示92%支持重启东门。现依据《物业管理条例》第十二条规定，发起全体业主签字表决。',
            'requirements': [
                {'label': '签字资格', 'value': '房产证登记业主'},
                {'label': '联署目标', 'value': '达到总户数2/3（即667户）以上有效签字'},
                {'label': '表决期限', 'value': '2025年8月1日至8月15日（每日19:00-21:00物业办公室集中办理）'}
            ],
            'plan': [
                {'icon': '▶', 'title': '开放时段', 'description': '每日5:00-23:00（夜间关闭后保留应急通道功能）'},
                {'icon': '▶', 'title': '管理措施', 'description': '新增门禁刷卡系统（拟从公共维修基金列支）'},
                {'icon': '▶', 'title': '成效预估', 'description': '缓解早晚高峰西门拥堵（预计减少排队时间8-12分钟）'}
            ]
        }
    }
    return jsonify(announcement_data)

@bp.route('/sign', methods=['POST'])
def sign():
    user_ip = request.remote_addr
    signature_data = request.form.get('signature_data')
    signature_name = request.form.get('signature_name')
    
    print(f"Debug: signature_data received: {signature_data[:100] if signature_data else 'None'}...")
    print(f"Debug: signature_name received: {signature_name}")
    
    if not signature_data or not signature_name:
        flash('请完成签字并输入姓名')
        return redirect(url_for('main.announcement'))
    
    # 验证和处理签名数据格式
    base64_data = None
    if signature_data.startswith('data:image/'):
        # 如果是完整的 data URI 格式，提取 base64 部分
        try:
            base64_data = signature_data.split(',')[1] if ',' in signature_data else signature_data
        except IndexError:
            flash('签字数据格式错误，请重新签字')
            return redirect(url_for('main.announcement'))
    else:
        # 如果是纯 base64 数据，直接使用
        base64_data = signature_data
    
    print(f"Debug: base64_data length: {len(base64_data) if base64_data else 0}")
    
    # 验证 base64 数据是否有效
    try:
        import base64
        decoded_data = base64.b64decode(base64_data)
        print(f"Debug: decoded data length: {len(decoded_data)}")
    except Exception as e:
        print(f"Debug: base64 decode error: {e}")
        flash('签字数据格式错误，请重新签字')
        return redirect(url_for('main.announcement'))
    
    # Check if user has already signed
    existing_user = User.query.filter_by(ip=user_ip).first()
    if existing_user:
        flash('您已经签过字了')
        return redirect(url_for('main.signatures'))

    try:        
        # Save new signature with image data
        new_user = User(ip=user_ip, signature=signature_name.strip(), signature_image=base64_data)
        db.session.add(new_user)
        db.session.commit()
        print(f"Debug: User saved with signature_image length: {len(base64_data)}")
        flash('感谢您的签字！')
        return redirect(url_for('main.signatures'))
    except Exception as e:
        print(f"Debug: Database save error: {e}")
        db.session.rollback()
        flash('签字保存失败，请重试')
        return redirect(url_for('main.announcement'))

@bp.route('/signatures')
def signatures():
    user_ip = request.remote_addr
    user = User.query.filter_by(ip=user_ip).first()
    signature = user.signature if user else None
    signature_image = user.signature_image if user else None
    return render_template('signatures.html', signature=signature, signature_image=signature_image)

@bp.route('/admin/all-signatures')
def all_signatures():
    """管理员查看所有签字记录"""
    all_users = User.query.all()
    return render_template('all_signatures.html', users=all_users)

@bp.route('/download-signature/<int:user_id>')
def download_signature(user_id):
    """下载指定用户的签字图片"""
    
    user = User.query.get_or_404(user_id)
    if not user.signature_image:
        flash('该用户没有签字图片')
        return redirect(url_for('main.all_signatures'))
    
    try:
        # 解码base64图片数据
        image_data = base64.b64decode(user.signature_image)
        
        # 创建文件名
        filename = f'signature_{user.id}_{user.signature or "unknown"}.png'
        
        return Response(
            image_data,
            mimetype='image/png',
            headers={'Content-Disposition': f'attachment; filename={filename}'}
        )
    except Exception as e:
        flash('下载签字图片失败')
        return redirect(url_for('main.all_signatures'))

@bp.route('/health')
def health_check():
    """健康检查端点 - 用于生产环境监控"""
    try:
        # 检查数据库连接
        db.session.execute('SELECT 1')
        return jsonify({
            'status': 'healthy',
            'database': 'connected',
            'environment': os.environ.get('FLASK_ENV', 'development')
        }), 200
    except Exception as e:
        return jsonify({
            'status': 'unhealthy',
            'error': str(e)
        }), 503

@bp.route('/version')
def version():
    """版本信息端点"""
    return jsonify({
        'application': 'SingVote',
        'version': '1.0.0',
        'environment': os.environ.get('FLASK_ENV', 'development')
    })